<template>
  <div class="container">
    <!--  header -->
    <div class="header_container">
      <div class="center">
        <van-image radius="0.2rem" height="1rem" width="1rem" :src="visitInfo.userImg" alt="" />
        <div class="author">
          <div class="title">{{ visitInfo.userName }}的拜访报告</div>
          <div class="time">{{ visitInfo.createTime }}</div>
        </div>
      </div>
      <van-icon v-if="visitInfo.forward == 1" class="share" size="25" color="#555" @click="shareVisit" name="share-o"></van-icon>
    </div>

    <!-- 详情主要数据 -->
    <div class="main_container">
      <!-- 固定模板 -->
      <div class="content_container">
        <div class="label">拜访日期：</div>
        <div class="content">{{ visitInfo.visitTime }}</div>
      </div>
      <div class="content_container">
        <div class="label">出差计划：</div>
        <div class="content">{{ visitInfo.reason || "无" }}</div>
      </div>
      <div class="content_container">
        <div class="label">客户：</div>
        <div class="content">{{ visitInfo.customerName }}</div>
      </div>
      <div class="content_container">
        <div class="label">客户联系人：</div>
        <div class="content">{{ visitInfo.contactsName }}</div>
      </div>
      <div class="content_container">
        <div class="label">项目：</div>
        <div class="content">{{ visitInfo.visitProjects || "无" }}</div>
      </div>
      <div class="content_container">
        <div class="label">拜访方式：</div>
        <div class="content">{{ visitInfo.visitType }}</div>
      </div>

      <!-- visitContentJson 这里是两个模板不同的部分，根据josn循环出来的。 -->
      <div class="content_container1" v-for="(value, key) in visitInfo.visitContentJson">
        <div class="label">{{ key }}：</div>
        <div v-html="value" class="content"></div>
      </div>

      <div class="content_container">
        <div class="label">费用开销：</div>
        <div class="content">{{ visitInfo.cost }}</div>
      </div>

      <!-- 图片 附件 -->
      <div v-if="visitInfo.imgs?.length > 0" class="content_container">
        <div class="label">图片：</div>
        <van-image v-for="(item, index) in visitInfo.imgs" :key="index" @click="seeInfoImg(index)" width="1rem" height="1rem" :src="item" />
      </div>
      <div v-if="visitInfo.files?.length > 0" class="files">
        <div class="label">附件：</div>
        <div class="file-items" v-for="(item, index) in visitInfo.files" :key="index">
          <span class="name">{{ item }}</span>
          <span class="load" @click="download(item)">下载</span>
        </div>
      </div>

      <!-- 已读 -->
      <div class="read_num">
        <!-- 
        --p：这个变量将定义百分比值（不带%符号）。
        --b：这个变量将定义边框的粗细。
        --c：这个变量将定义主要颜色。
       -->
        <div class="pie" style="--b: 10px; --c: #bdc1c4" :style="{ '--p': percent }"></div>
        <div class="num" @click="showReadNum()">{{ _length || 0 }}人已读</div>
      </div>

      <!-- 评论列表 -->
      <div class="comment_list" v-if="commentList?.length > 0">
        <div class="comment_label">评论 {{ commentTotal }}</div>
        <div class="item_container" v-for="item in commentList">
          <van-image width="1rem" height="1rem" radius="0.2rem" class="limg" :src="item.userImg" alt="" />
          <div class="item_content">
            <div class="name">{{ item.userName }}</div>
            <div class="new_text">
              <span class="comment_text">{{ item.context }}</span>
            </div>
            <div class="original_text" v-if="item.cid">
              <div class="line"></div>
              <div class="original_content">{{ item.cid }}</div>
            </div>
            <div class="item_time">
              <div class="time_label">{{ item.createTime }}</div>
              <div v-if="item.userId != Local.get('userId')" class="reply" @click="replyHandle(item)">回复</div>
            </div>
          </div>
        </div>
      </div>
      <div class="plar" v-else>暂无评论...</div>
    </div>

    <!-- 评论 -->
    <div class="comment_container">
      <Field v-model="commentVlaue" type="textarea" autosize @update:model-value="valueChange" @clear="close" clearable :placeholder="commentPlaceholder" ref="focusInput" />
      <Button size="samll" type="primary" :disabled="!commentVlaue" class="send_btn" @click="sendHandle()">{{ textContent ? "回复" : "评论" }}</Button>
    </div>

    <!-- 已读未读弹框 -->
    <van-dialog v-model:show="showFlag" :showConfirmButton="false" :closeOnClickOverlay="true">
      <!-- title -->
      <div class="navbar">
        <div class="options">
          <div class="option" :class="{ option_active: currentIndex == 1 }" @click="readClick(1)">
            <div class="text">已读{{ _length }}</div>
          </div>
          <div class="option mr10" :class="{ option_active: currentIndex == 0 }" @click="readClick(0)">
            <div class="text">未读{{ length_ }}</div>
          </div>
        </div>
        <div class="close">
          <van-icon name="cross" @click="showFlag = false" />
        </div>
      </div>

      <!-- 列表已读未读 -->
      <div class="read_list">
        <div class="read_item" v-for="item in readList">
          <div>
            <van-image radius="0.2rem" width="45" height="45" :src="item.userImg" alt="" />
          </div>
          <div class="name">{{ item.userName }}</div>
        </div>
      </div>
    </van-dialog>

    <!-- 分享时获取人员列表 -->
    <VanDialog v-model:show="showUser" :closeOnClickOverlay="true" :showConfirmButton="false" title="深圳市斯贝达电子有限公司">
      <User :isType="5" @back="back" @callback="setCheckUser"></User>
    </VanDialog>
  </div>
</template>
<script setup name="detail">
import { ref, onMounted, reactive } from "vue";
import { ImagePreview, Notify, Dialog, Button, Toast, Field } from "vant";
import { useRoute } from "vue-router";

import { getVisitInfoById, getReadList, updateRead, addVisitComment, visitCommentList, visitShare } from "@/api";

import { Local } from "@/utils/storage";
import User from "@/views/user/index.vue";
const VanDialog = Dialog.Component;
const route = useRoute();

// 分享拜访记录
const showUser = ref(false);
const shareVisit = () => {
  showUser.value = true;
};

const back = () => {
  showUser.value = false;
};

// 分享时获取人员后的回调
const setCheckUser = async (list) => {
  const arr = list
    ?.map((v) => {
      return v.userId;
    })
    .toString();
  let data = {
    id: visitInfo.id,
    user: arr,
  };
  await visitShare(data);
  showUser.value = false;
  Toast("分享成功");
};

//初始化数据 获取 带过来的参数
const currentId = ref("");
onMounted(async () => {
  if (route?.query.type) {
    currentId.value = route.query.id;
  }
  if (currentId.value) {
    await _getVisitInfoById(currentId.value);
    await setRead(currentId.value, Local.get("userId"));
    // 获取已读和未读的列表 获取长度length显示
    await getVisitCommentList();
    await getCurrenReadList(0);
    await getCurrenReadList(1);
  }
});

// 获取数据详情
const visitInfo = reactive({});
const commentPlaceholder = ref(``);
const _getVisitInfoById = async (id) => {
  let { data } = await getVisitInfoById({ id });
  // 处理 visitContentJson 的数据
  data.visitContentJson = JSON.parse(data.visitContentJson);
  for (const key in data.visitContentJson) {
    data.visitContentJson[key] = data.visitContentJson[key]?.replace(/\\n/g, "<br>");
    data.visitContentJson[key] = data.visitContentJson[key]?.replace(/"/g, "");
  }
  console.log(data.visitContentJson);

  if (data.imgs) data.imgs = data.imgs.split(",");
  if (data.files) data.files = data.files.split(",");
  Object.assign(visitInfo, data);
  commentPlaceholder.value = `评论${visitInfo.userName}的拜访报告`;
  console.log("visitInfo", visitInfo);
};

// 图片点击查看预览
const seeInfoImg = (index) => {
  ImagePreview({
    images: visitInfo.imgs,
    startPosition: index,
    closeable: true,
  });
};

// 下载附件
const download = (url) => {
  Notify({ type: "primary", message: "正在下载中" });
  let ele = document.createElement("a");
  ele.download = "附件";
  ele.style.display = "none";
  ele.href = url;
  document.body.appendChild(ele);
  ele.click();
  document.body.removeChild(ele);
};

// 进入详情页面  标记为已读操作
const setRead = async (id, userId) => {
  await updateRead({ id, userId });
};

// 获取已读,未读的列表数据
const readList = ref([]);
const _length = ref(0);
const length_ = ref(0);
const getCurrenReadList = async (e) => {
  let res = await getReadList({
    id: currentId.value,
    state: e, // 0 未读 1 已读
  });
  readList.value = res.data;
  if (e == 1) {
    _length.value = res.data?.length;
  } else {
    length_.value = res.data?.length;
  }
};

//展示已读/未读弹框
const percent = ref("60");
const showFlag = ref(false);
const currentIndex = ref(1);
const showReadNum = () => {
  showFlag.value = true;
  currentIndex.value = 1;
  // 重置到已读
  getCurrenReadList(currentIndex.value);
};

//点击已读/未读
const readClick = (num) => {
  currentIndex.value = num;
  getCurrenReadList(num);
};

//回复  评论
const focusInput = ref();
let commentVlaue = ref("");
let commentUser = ref();
let isRecover = ref(false);
const textContent = ref("");
let commentTotal = ref(0);
let commentList = ref([]);
const replyHandle = (row) => {
  isRecover.value = true;
  setTimeout(() => {
    focusInput.value.focus();
  }, 300);
  commentUser.value = row.userName;
  commentPlaceholder.value = "";
  textContent.value = row.context;
  commentVlaue.value = `回复：@${commentUser.value}`;
};

// 获取评论列表
const getVisitCommentList = async () => {
  let res = await visitCommentList({ id: visitInfo.id });
  commentList.value = res.data;
  commentTotal.value = res.data?.length;
  console.log("获取评论列表", res);
};

// 值发生改变时
const valueChange = (e) => {
  if (!e) {
    textContent.value = "";
  }
};

//发送
const sendHandle = async () => {
  let data = {
    visitId: visitInfo.id,
    context: commentVlaue.value,
    userId: Local.get("userId"),
    cid: textContent.value,
  };
  console.log(data);
  await addVisitComment(data);
  Toast("发送成功");
  getVisitCommentList();
  commentVlaue.value = "";
  textContent.value = "";
  commentPlaceholder.value = `评论${visitInfo.userName}的拜访报告`;
};
</script>
<style>
@import "../../assets/styles/index.scss";
</style>
<style scoped lang="scss">
@import "./index.scss";
</style>
